package ext.tianma.part.validators;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.PropertyResourceBundle;

import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.WTObject;
import wt.fc.WTReference;
import wt.inf.container.WTContained;
import wt.inf.container.WTContainer;
import wt.inf.library.WTLibrary;
import wt.inf.team.ContainerTeam;
import wt.inf.team.ContainerTeamHelper;
import wt.inf.team.ContainerTeamManaged;
import wt.inf.team.ContainerTeamManagedInfo;
import wt.inf.team.ContainerTeamReference;
import wt.org.GenericDirectoryContextProvider;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.project.Role;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.team.Team;
import wt.team.TeamManaged;
import wt.team.TeamReference;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfProcess;

import com.ptc.core.ui.validation.DefaultSimpleValidationFilter;
import com.ptc.core.ui.validation.UIValidationCriteria;
import com.ptc.core.ui.validation.UIValidationKey;
import com.ptc.core.ui.validation.UIValidationStatus;
import com.ptc.windchill.enterprise.revisionControlled.insertWizardResource;


public class BatchUpdatePartsValidators extends DefaultSimpleValidationFilter
{
	public BatchUpdatePartsValidators(){}
	
	private static final String CLASSNAME = BatchUpdatePartsValidators.class.getName();
	private static String  path="";
	private static String path1="";
	static
    {
        try
        {
          WTProperties wtproperties = WTProperties.getLocalProperties();
            path = (WTProperties.getLocalProperties()).getProperty("ext.tianma.part.verbose");
            path1 = (WTProperties.getLocalProperties()).getProperty("ext.tianma.part1.verbose");
          System.out.println(" --------------------------path ="+path+ "---------- part1 ="+path1);
        }
        catch (Throwable throwable)
        {
            throwable.printStackTrace(System.err);
            throw new ExceptionInInitializerError(throwable);
        }
    }
	
	
	public UIValidationStatus preValidateAction(UIValidationKey uivalidationkey, UIValidationCriteria uivalidationcriteria)
	{
		UIValidationStatus uivalidationstatus = UIValidationStatus.HIDDEN;
		boolean bool = SessionServerHelper.manager.isAccessEnforced();
		
		try
		{
			SessionServerHelper.manager.setAccessEnforced(false);
			WTReference wtreference = uivalidationcriteria.getContextObject();
			if (wtreference == null)
			{
				return uivalidationstatus;
			}
			
			Persistable persistable = wtreference.getObject();
			WTPrincipal cur_user = SessionHelper.manager.getPrincipal();
			System.out.println("-----------------------persistable="+persistable+"-------cur_user.getName="+cur_user.getName());
			Role role=Role.toRole("BOMEngineer");
	    	System.out.println(" ------------------ 直接  role ="+role.getDisplay());
	    	
	    	if(persistable instanceof WTLibrary)
	    	{
				WTContained containedObj = (WTContained) persistable;
				WTContainer container=(WTContainer) persistable;
		    	//WTContainer container = containedObj.getContainer();
		    		System.out.println("-----------进入WTLibrary");
		    		System.out.println(" -------------container ="+container);
//		    	if(container instanceof ContainerTeamManaged)
//		    	{
		    		System.out.println(" -----------进入容器团队");
		    		ContainerTeamManaged ctm = (ContainerTeamManaged) container;
					ContainerTeam containerTeam = ContainerTeamHelper.service.getContainerTeam(ctm);
					ArrayList list=containerTeam.getAllPrincipalsForTarget(role);
					System.out.println(" -------------------- list.size()="+list.size());
					
					for(Iterator it = list.iterator();it.hasNext();)
					{
						WTPrincipalReference principalref = (WTPrincipalReference) it.next();
						
						WTPrincipal principal=principalref.getPrincipal();
						
						System.out.println("-------------principal="+principal);
						if(principal instanceof WTUser)
						{
							System.out.println("------------- ent .... WTUser  ");
							if(principal.getName().equals(cur_user.getName())&& path.equals(container.getName()))
							{
								System.out.println("path 用户：已经存在的用户名："+principalref.getName());
								uivalidationstatus = UIValidationStatus.ENABLED;
								return uivalidationstatus;
							}
							
							if(principal.getName().equals(cur_user.getName())&& path1.equals(container.getName()))
							{
								System.out.println("path 1 用户：已经存在的用户名："+principalref.getName());
								uivalidationstatus = UIValidationStatus.ENABLED;
								return uivalidationstatus;
							}
							
						}
						if(principal instanceof WTGroup)
						{
							System.out.println("------------- ent .... WTGroup  ");
							Enumeration members= ((WTGroup)principal).members();
							while(members != null && members.hasMoreElements())
							{
								wt.org.WTPrincipal wtp1 = ((wt.org.WTPrincipal)members.nextElement());
								if(wtp1.getName().equals(cur_user.getName()) && path.equals(container.getName()))
								{
									System.out.println("path 组：已经存在的用户名："+wtp1.getName());
									uivalidationstatus = UIValidationStatus.ENABLED;
									return uivalidationstatus;
								}
								if(wtp1.getName().equals(cur_user.getName()) && path1.equals(container.getName()))
								{
									System.out.println("path1  组：已经存在的用户名："+wtp1.getName());
									uivalidationstatus = UIValidationStatus.ENABLED;
									return uivalidationstatus;
								}
							}
						}
						
					}
			    	
//					String[] roleKey = {"BOMEngineer"};
//			    	boolean bomengieer=isExistInRole(roleKey, container, cur_user.getName());
//			    	String name=container.getName();//存储库名称
//			    	System.out.println("--------------------name="+name);
//			    	if(persistable instanceof WTLibrary)
//			    	{
//						//BOM工程师
//						//boolean issubmiter = ext.com.workflow.WorkflowUtil.isProcessRoleParticipant(part, "BOMEngineer");
//				    	System.out.println("-----------bomengieer="+bomengieer);
//						//管理员
//						//boolean isadmin = checkIsAdmin((WTUser) cur_user);
//						if(name.equals("") && bomengieer)
//						{
//							uivalidationstatus = UIValidationStatus.ENABLED;
//							return uivalidationstatus;
//						}
//						if(name.equals("") && bomengieer)
//						{
//							uivalidationstatus = UIValidationStatus.ENABLED;
//							return uivalidationstatus;
//						}
//			    	}
//		    	}
	    	}
			
			return uivalidationstatus;
		}
		catch (WTException e)
		{
			e.printStackTrace();
			return uivalidationstatus;
		}
		finally 
    	{
    		SessionServerHelper.manager.setAccessEnforced(bool);
        }
		
	}
	/**
	 * 检查用户是否是管理员组成员
	 * 
	 * @param wtuser
	 *           用户
	 * @return 如果是管理员组成员true ；不是管理员组成员为false
	 * @exception WTException
	 */
	public static boolean checkIsAdmin(WTUser wtuser) throws WTException
	{
		boolean flag = false;
		if(wtuser==null)
			return false;
		GenericDirectoryContextProvider genericdirectorycontextprovider = new GenericDirectoryContextProvider(null);
	     WTGroup wtgroup = OrganizationServicesHelper.manager.getGroup("Administrators", genericdirectorycontextprovider);
	     flag = wtgroup.isMember(wtuser);
		return flag;
	}
	
	
	 /**
     * 获取properties中的值
     *
     * @param propertityFile
     *            properties的文件名
     * @param keyInProperties
     *            properties的key值
     * @return String properties的值
     **/
    public static String getPropertiesValue(String propertityFile, String keyInProperties) throws WTException
    {
        String valueInProperties = "";

        PropertyResourceBundle prBundle = (PropertyResourceBundle) PropertyResourceBundle.getBundle(propertityFile);
        try
        {
            byte[] temp = null;
            temp = keyInProperties.getBytes("GB2312");
            keyInProperties = new String(temp, "ISO-8859-1");
            temp = prBundle.getString(keyInProperties).getBytes("ISO-8859-1");
            valueInProperties = new String(temp, "GB2312");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return valueInProperties.trim();

    }

	
	
}
